package com.itheima.utils;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class POIUtils2 {

   private static final String xls = "xls";
   private static final String xlsx = "xlsx";
   private final static String DATE_FORMAT = "yyyy/MM/dd";

   //读入excel,解析后返回
   public static List<String[]> readExcel(MultipartFile file) throws IOException {
      List<String[]> list = new ArrayList<String[]>();
      String[] cells = null;
      //校验文件
      checkFile(file);
      //读取excel文件
      //1.获取工作簿
      Workbook workbook = getWorkbook(file);
      if (workbook != null) {
         //2.遍历所有sheet表
         for (int sheetNum = 0; sheetNum < workbook.getNumberOfSheets(); sheetNum++) {
            //3.获取当前sheet表
            Sheet sheet = workbook.getSheetAt(sheetNum);
            if (sheet == null) {
               continue;
            }
            //4.获取开始的第一行
            int firstRowNum = sheet.getFirstRowNum();
            //5.获取结束行
            int lastRowNum = sheet.getLastRowNum();
            //6.跳过开始的第一行(标题)开始执行
            for (int rowNum = firstRowNum + 1; rowNum <= lastRowNum; rowNum++) {
               //7.获取当前行对象
               Row row = sheet.getRow(rowNum);
               if (row == null) {
                  continue;
               }
               //8.获取当前行开始的单元格
               int firstCellNum = row.getFirstCellNum();
               //9.获取当前行结束的单元格
               int lastCellNum = row.getPhysicalNumberOfCells();

               cells = new String[lastCellNum];
               //10.遍历当前行
               for (int cellNum = firstCellNum; cellNum < lastCellNum; cellNum++) {
                  //11.封装数组
                  Cell cell = row.getCell(cellNum);
                  //12.调用获取值的方法
                  String cellValue = getCellValue(cell);
                  cells[cellNum] = cellValue;
               }
               list.add(cells);
            }
         }
         //释放资源
         workbook.close();
      }
      return list;
   }

   //根据cell的数据类型进行赋值字符串
   private static String getCellValue(Cell cell) {

      if (cell == null) {
         return "";
      }
      String cellValue = "";
      //如果当前单元格内容是日期格式,需要特殊处理
      String dataFormatString = cell.getCellStyle().getDataFormatString();
      if (dataFormatString.equals("m/d/yy")) {
         cellValue = new SimpleDateFormat(DATE_FORMAT).format(cell.getDateCellValue());
         return cellValue;
      }

      //如果当前单元格内容是小数格式,避免数字1转为1.0字符串
      if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
         cell.setCellType(Cell.CELL_TYPE_STRING);
      }

      //判断数据类型
      switch (cell.getCellType()) {
         case Cell.CELL_TYPE_STRING:
            cellValue = String.valueOf(cell.getStringCellValue());
            break;
         case Cell.CELL_TYPE_NUMERIC:
            cellValue = String.valueOf(cell.getNumericCellValue());
            break;
         case Cell.CELL_TYPE_BOOLEAN:
            cellValue = String.valueOf(cell.getBooleanCellValue());
            break;
         case Cell.CELL_TYPE_FORMULA:
            cellValue = String.valueOf(cell.getCellFormula());
            break;
         case Cell.CELL_TYPE_BLANK:
            cellValue = "";
            break;
         case Cell.CELL_TYPE_ERROR:
            cellValue = "非法字符";
            break;

      }
      return cellValue;
   }

   //根据文件类型动态生成工作簿对象
   private static Workbook getWorkbook(MultipartFile file) {
      //1.获取文件名称
      String filename = file.getOriginalFilename();
      Workbook workbook = null;
      try {

         InputStream inputStream = file.getInputStream();
         if (filename.endsWith(xls)) { //为xls格式文件时
            workbook = new HSSFWorkbook(inputStream);
         }
         if (filename.endsWith(xlsx)) {//为xlsx格式文件时
            workbook = new XSSFWorkbook(inputStream);
         }
      } catch (IOException e) {
         e.printStackTrace();
      }

      return workbook;

   }

   //校验文件正确性
   private static void checkFile(MultipartFile file) throws IOException {
      //1.检查文件是否存在
      if (file == null) {
         throw new FileNotFoundException("文件不存");
      }
      //2.检查文件格式是否正确
      String originalFilename = file.getOriginalFilename();
      if (!originalFilename.endsWith(xls) && !originalFilename.endsWith(xlsx)) {
         throw new IOException(originalFilename + "不是excel文件");
      }

   }
}
